package org.ym.basic;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.ym.basic.base.ICurrentUser;

/**
 * @author ym
 */
public class ContextUtils {
    /**
     * 获取当前用户
     * @return 当前用户
     */
    public static final ICurrentUser getCurrentUser(){
        ICurrentUser sysUser=null;
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            Authentication auth = securityContext.getAuthentication();
            if (auth != null) {
                Object principal = auth.getPrincipal();
                if (principal instanceof ICurrentUser) {
                    sysUser=(ICurrentUser)principal;
                }
            }
        }
        return sysUser;
    }

    public final static void setCurrentUser(ICurrentUser sysUser){
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            UserDetails userDetails = (UserDetails)sysUser;
            Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
            securityContext.setAuthentication(auth);
        }
    }
}
